# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import os, base64,re

htmlDoc="""
	<!DOCTYPE HTML>
	<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
	<img src="" alt="1" />
	<img src="" alt="2" />
	<img src="" alt="3" />
	</body>
	</html>
"""

#脚本运行的根目录
homedir = os.getcwd()
logs=open('f.txt','a')
'''
	解析使用base64编码的图片节点数据
'''
def resloveBaseData(data,index):
	print u"解析base64编码的图片第【",index,u"】张开始"
	#图片的类型
	_imgType=re.search(r'(?<=:).*(?=;)',data).group().split("/")[1]
	#生成的图片名称
	fileName="".join((str(index),".",_imgType))
	print fileName
	#图片数据
	_imgData=re.search(r'(?<=,).*',data).group()
	logs.write("\n")
	logs.write(_imgData)
	base64ToFile(_imgData,fileName)
	print u"解析base64编码的图片第【",index,u"】张结束"
	return "","img\\",fileName;

'''
	base64数据转图片
'''
def base64ToFile(baseData,fileName):
	imgData = base64.b64decode(baseData)
	imgFile = open(os.path.join(homedir,"img",fileName),'wb')
	imgFile.write(imgData)
	imgFile.close()



with open("1.html","r") as f:
	htmlDoc=f.read();

soup = BeautifulSoup(htmlDoc)
#获取页面所有的img节点
listImg=soup.find_all('img')
#print listImg[0]
#img节点的下标
index=0;
for img in listImg:
	_temp=listImg[index]['src']
	#修改图片集合中下标为index的图片的alt属性
	listImg[index]['src']=resloveBaseData(_temp,index)
	#下标增加
	index+=1
print soup






with open("a.html","wb") as f:
	f.write(soup.encode('utf-8'))


#测试
#resloveBase64("",1)